package com.wzapp.sitposture.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密类（封装jdk自带的md5加密方法）
 *
 * @author ql
 * @date 2017年10月12日 下午4:14:22
 */
public class MD5Util {

    public static String encrypt(String source) {
        return encodeMd5(source.getBytes());
    }
    
    /**
     * 
     * 加盐MD5加密 <br/> 
     * 
     * @author ql
     *
     * @param source
     * @param salt
     * @return
     */
    public static String encrypt(String source, String salt) {
        return encodeMd5(source.getBytes(), salt.getBytes());
    }
    
    private static String encodeMd5(byte[] source) {
        try {
            return encodeHex(MessageDigest.getInstance("MD5").digest(source));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    
    private static String encodeMd5(byte[] source, byte[] salt) {
        try {
        	MessageDigest md = MessageDigest.getInstance("MD5");
        	//计算MD5函数  
            md.update(salt);
            return encodeHex(md.digest(source));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    private static String encodeHex(byte[] bytes) {
        StringBuffer buffer = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10)
                buffer.append("0");
            buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buffer.toString();
    }


    public static void main(String[] args) {
        System.out.println(MD5Util.encrypt("e10adc3949ba59abbe56e057f20f883e", "x6iCvcKMs1d4eYJiPRVAV1J4jLQziT9e"));
    }
}
